{
 "cells": [
  {
   "metadata": {
    "collapsed": true
   },
   "cell_type": "markdown",
   "source": "# 感知机的实现",
   "id": "9fddf3d0c31ed23c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-25T03:21:42.972003Z",
     "start_time": "2025-09-25T03:21:42.959271Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 简单与门实现\n",
    "def AND(x1, x2):\n",
    "    w1, w2, theta = 0.5, 0.5, 0.7\n",
    "    tmp = x1 * w1 + x2 * w2\n",
    "    if tmp <= theta:\n",
    "        return 0\n",
    "    elif tmp > theta:\n",
    "        return 1"
   ],
   "id": "75608be684c41186",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-25T03:22:39.728429Z",
     "start_time": "2025-09-25T03:22:39.721164Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(AND(0, 0)) # 输出0\n",
    "print(AND(1, 0)) # 输出0\n",
    "print(AND(0, 1)) # 输出0\n",
    "print(AND(1, 1)) # 输出1"
   ],
   "id": "fa222d50dcae9e62",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "0\n",
      "0\n",
      "1\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import numpy as np\n",
    "\n",
    "# 与门、与非门、或门是具有相同构造的感知机，区别只在于权重参数的值\n",
    "def AND1(x1,x2):\n",
    "    x = np.array([x1,x2])\n",
    "    w = np.array([0.5,0.5])\n",
    "    b = -0.7\n",
    "    tmp = np.sum(w*x)+b\n",
    "    if tmp <= 0:\n",
    "        return 0\n",
    "    else:\n",
    "        return 1\n",
    "\n",
    "def NAND(x1,x2):\n",
    "    x = np.array([x1,x2])\n",
    "    w = np.array([-0.5,-0.5])\n",
    "    b = 0.7\n",
    "    tmp = np.sum(w*x)+b\n",
    "    if tmp <= 0:\n",
    "        return 0\n",
    "    else:\n",
    "        return 1\n",
    "\n",
    "def OR(x1,x2):\n",
    "    x = np.array([x1,x2])\n",
    "    w = np.array([0.5,0.5])\n",
    "    b = -0.2\n",
    "    tmp = np.sum(w*x)+b\n",
    "    if tmp <= 0:\n",
    "        return 0\n",
    "    else:\n",
    "        return 1\n",
    "# 通过与非门和或门实现异或门\n",
    "def XOR(x1, x2):\n",
    "    s1 = NAND(x1, x2)\n",
    "    s2 = OR(x1, x2)\n",
    "    y = AND(s1, s2)\n",
    "    return y\n",
    "\n"
   ],
   "id": "a6385a57e72efa9e"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
